package com.mgface.foundation.framework.core.freemarker;

import freemarker.template.TemplateException;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import org.springframework.web.servlet.view.freemarker.FreeMarkerView;
import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver;

import java.io.IOException;
import java.util.Properties;

/**
 * @author wanyuxiang
 * @version 1.0
 * @project store-root
 * @create 2017-05-12 18:51
 * @desc 参考http://blog.csdn.net/w329636271/article/details/53232372
 **/
@Configuration
public class FreemarkerConfiguration {
    @Bean
    public FreeMarkerConfigurer freemarkerConfig() throws IOException, TemplateException {
        FreeMarkerConfigurer configurer = new FreeMarkerConfigurer();
        configurer.setTemplateLoaderPath("classpath:/templates/");
        Properties prop = new Properties();
        prop.put("defaultEncoding","UTF-8");
        prop.put("url_escaping_charset","UTF-8");
        prop.put("locale","zh_CN");
        prop.put("template_update_delay","3600");
        prop.put("tag_syntax","square_bracket");
        prop.put("whitespace_stripping","true");
        prop.put("classic_compatible","true");
        prop.put("number_format","0.######");
        prop.put("boolean_format","true,false");
        prop.put("datetime_format","yyyy-MM-dd");
        prop.put("date_format","yyyy-MM-dd");
        prop.put("time_format","HH:mm:ss");
        prop.put("object_wrapper","freemarker.ext.beans.BeansWrapper");
        //freemarkerVariables
        configurer.setFreemarkerSettings(prop);
        return configurer;
    }


    @Bean
    @ConditionalOnMissingBean(name = "freeMarkerViewResolver") // 没有配置freeMarkerViewResolver这个bean的话，会自动构造一个freeMarkerViewResolver
    @ConditionalOnProperty(name = "spring.freemarker.enabled", matchIfMissing = true) //配置文件中开关开启的话，才会构造
    public FreeMarkerViewResolver getFreemarkerViewResolver() {
        FreeMarkerViewResolver freeMarkerViewResolver = new FreeMarkerViewResolver();
        freeMarkerViewResolver.setCache(false);
        freeMarkerViewResolver.setSuffix(".ftl");
        freeMarkerViewResolver.setContentType("text/html; charset=UTF-8");
        //freeMarkerViewResolver.setOrder(1);
        //freeMarkerViewResolver.setViewNames("ftl/*");
        freeMarkerViewResolver.setViewClass(FreeMarkerView.class);
        return freeMarkerViewResolver;
    }
}
